package org.cuatrovientos.erp.dao;


import java.util.List;

import org.cuatrovientos.erp.model.City;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
 * 
 * @author CARLOS
 *
 */
public class CityDAO implements CityDAOInterface{


	@Autowired
	 private SessionFactory sessionFactory;
	
	public CityDAO(){
		
	}
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	 @Transactional(readOnly = true)
		public City selectById(int id) {
			City city= (City) getSession().get(City.class, id);
		    return city;
		}

	 /*
		 * retrieves all products from db
		 * @return List of products
		 */
		 @Transactional(readOnly = true)
		public List<City> selectAll() {
		 
		    List<City> cities = getSession().createQuery("from City").list();
		    return cities;
		}

		 /*
			 * inserts a new product in database
			 * retrieves generated id and sets to product instance
			 * @param new product
			 */
			 @Transactional
			public void insert(City city) {
			    Integer id = (Integer) getSession().save(city);
			    city.setId(id);           
			}

				/*
				 * updates product
				 * @param product to update
				 */
				 @Transactional
				public void update(City city) {
					getSession().merge(city);
				}

				 /*
					 * delete given product
					 * @param product to delete
					 */
					 @Transactional
					public void delete(City city) {
						getSession().delete(city);
					}

					 /**
					  * deletes using id
					  */
					 @Transactional
					public void deleteById(int id) {
						 City city = (City) getSession().load(City.class,id);
						 getSession().delete(city);
					}

					 /**
					  * performs search operation
					  */
					 @Transactional(readOnly = true)
					public List<City> search(String name) {
						   Query query = getSession().createQuery("from City c where c.name like :name");
				           query.setParameter("name", "%"+name+"%");
				           
				           List<City> cities = query.list();
						
				           return cities;
					}

}
